package com.lt.integration.jpa.validation;

import com.lt.integration.jpa.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 枚举参数校验处理类
 * @author: xiaobin
 * @create: 2020-08-09 14:23
 */
public class EnumValidator implements ConstraintValidator<EnumValid, String> {

    private static final Logger log = LoggerFactory.getLogger(EnumValidator.class);

    // 枚举校验注解
    private EnumValid annotation;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        Class<?> cls = annotation.target();
        boolean ignoreEmpty = annotation.ignoreEmpty();
        String[] values = annotation.values();

        // 如果忽略空 && value是空的 直接返回true
        if (ignoreEmpty && StringUtils.isEmpty(value)) {
            return true;
        }

        if (StringUtils.isEmpty(value)) {
            return false;
        }

        if (null != values && values.length > 0) {
            for (String str : values) {
                if (value.equals(str)) {
                    return true;
                }
            }
            return false;
        }

        boolean result = false;
        // target为枚举，并且value有值，或者不忽视空值，才进行校验
        if (cls.isEnum()) {
            Object[] objects = cls.getEnumConstants();
            try {
                Method method = cls.getMethod("name");
                for (Object obj : objects) {
                    Object code = method.invoke(obj);
                    if (value.equals(code.toString())) {
                        result = true;
                        break;
                    }
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                log.warn("EnumValidator call isValid() method exception.");
                result = false;
            }
        } else {
            result = true;
        }
        return result;
    }
}